package com.bbseguros.pesquisador.converter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.bbseguros.pesquisador.bean.MonitoramentoBean;
import com.bbseguros.pesquisador.dao.MonitoramentosDAO;

/**
 * @author hmsilva
 *
 */
public class Converter extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(Converter.class);

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doProcess(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doProcess(request, response);
    }
    
    /**
     * @param request
     * @param response
     * @throws IOException
     */
    public void doProcess(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	StringBuffer buffer = new StringBuffer(); 
    	String flag = request.getParameter("param");
    	try {    		
        	
        	MonitoramentosDAO dao = MonitoramentosDAO.getInstance();
        	//ArrayList<MonitoramentoBean> list = dao.selectAllMonitoramentos();
        	ArrayList<MonitoramentoBean> list = dao.selectToConverter();
        	MonitoramentoBean bean = null;
        	
        	logger.debug("ITENS RETORNADOS DO SELECT : "+list.size());
        	
        	for (int i = 0; i < list.size(); i++) {
        		
        		bean = list.get(i);
        		if(doUpdate(bean, flag)){
        			
        			//logger.debug("ANTES: "+bean.getResultadoPesquisa());
        			//ChangeToXML xmlChange = new ChangeToXML(bean.getResultadoPesquisa());
        			
        			//validadndo codigo do pesquisador
        			bean = verifyCodPesquisador(bean);
        			
        			String idUsuario = String.valueOf(bean.getCodigoUsuario());
        			String xml = bean.getResultadoPesquisa();
        			
        			logger.debug("idUsuario: "+idUsuario);
        			//logger.debug("XML: "+xml);
        			
        			buffer.append("<p><small>idUsuario: "+idUsuario+"</small></p>");
        			buffer.append("<p><small>XML: ' "+xml+" '</small></p>");
        			        			
        			//bean.setResultadoPesquisa(xml);
        			//logger.debug("bean.toString(): "+bean.toString());
        			
        			bean = callService(bean);
        			
        			boolean insert = dao.updateMonitoramento(bean);
        			buffer.append("<p>  ==>>> UPDATED = "+ insert +"</p>");
        			buffer.append("<p>  ==>>> SEND = "+ bean.getStatusEnvio() +"</p>");
        			
        			buffer.append("<p>------------------------------------------------</p>");
        		}
        		
        		Thread.sleep(100);
    		}
        	
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
    	
    	
    	ServletOutputStream out = response.getOutputStream();
    	out.write((""+buffer.toString()+"").getBytes());		
		out.close();
    }
    
    private boolean doUpdate(MonitoramentoBean bean, String flag){
    	try {
    		
    		logger.debug("---------------------- VALIDANDO REENVIO ----------------------");
        	logger.debug("---------------------- FLAG:  "+flag+  " ----------------------");
        	logger.debug("---------------------- STATUS ENVIO: "+bean.getStatusEnvio()+"----------------------");
        	logger.debug("---------------------- PROTOCOLO: "+bean.getProtocolo()+" ----------------------");
        	
        	if(flag != null && flag.equals("true")){
        		logger.debug("SEND UPDATE TRUE");
        		return true;
        		
        	} else if(bean.getStatusEnvio().equals("0")){
        		logger.debug("SEND UPDATE TRUE");
        		return true;
        		
        	} else if(bean.getProtocolo() == null || bean.getProtocolo().equals("")){
        		logger.debug("SEND UPDATE TRUE");
        		return true;
        		
        	} else {
        		return false;
        	}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return false;
		}    	
    	
    }
    
    /**
     * @param bean
     * @return
     */
    public MonitoramentoBean callService(MonitoramentoBean bean){
    	WebServiceClient client = new WebServiceClient();
    	
    	//---------------------------------
    	bean.setProtocolo("0");
    	bean.setStatusEnvio("0");
    	//---------------------------------
    	
    	try {
    		String xml = client.callService(WebServiceClient.SERVICE_AGENDAMENTO_, bean.getResultadoPesquisa());
			
    		xml.replaceAll("&lt;", "<");
    		xml.replaceAll("&gt;", ">");
    		xml.replaceAll("&#13;", "");
    		
    		String codigoRetorno = client.getXMLValue("CODIGO", xml); 
    		logger.debug("CODIGO DE RETORNO: "+codigoRetorno);
    		
    		if(codigoRetorno.equals("9999") || codigoRetorno.equals("999") ){
    			
    			String recibo = client.getXMLValue("RECIBO", xml);
    			logger.debug("RECIBO: "+recibo);
    			
    			if(recibo != null && !recibo.equals("")){
    				bean.setProtocolo(recibo);
        			bean.setStatusEnvio("1");	
    			}    			
    		}
    			
    		String message = client.getXMLValue("CODIGO", xml) +" - "+client.getXMLValue("MSG", xml);    		
    		bean.setMsgReturn(message);    		  		
    		
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		logger.debug("bean gerado: "+bean.toString());
    	return bean;    	
    }
    
    /**
     * @param bean
     * @return
     */
    private MonitoramentoBean verifyCodPesquisador(MonitoramentoBean bean){
    	
    	try {			
    		InputStream is = new ByteArrayInputStream(bean.getResultadoPesquisa().getBytes());
    		Document doc = null;
    		
    		try {
    			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    			DocumentBuilder db = dbf.newDocumentBuilder();
    			doc = db.parse(is);
    			doc.getDocumentElement().normalize();
    			
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		
    		logger.debug("XML recebido: "+bean.getResultadoPesquisa());
    		
    		String codPesq = getElementValue(doc, "COD_PESQUISADOR");		
    		if(codPesq == null || codPesq.equals("")){
    			bean = changeCodPesq(bean);
    			
    			logger.debug("codPesq recebido: '"+codPesq+"'");
            	logger.debug("novo codPesq : "+bean.getCodigoUsuario());
    		}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
    	
		return bean;
    }
    
    /**
     * @param bean
     * @return
     */
    private MonitoramentoBean changeCodPesq(MonitoramentoBean bean){  
    	
    	String xml = bean.getResultadoPesquisa();
    	String idPesq = bean.getCodigoUsuario();
    	
    	bean.setResultadoPesquisa(WebServiceClient.changeXMLValue("COD_PESQUISADOR",xml,idPesq));    	
    	return bean;
    }
   
	/**
	 * @param doc
	 * @param elementName
	 * @return
	 */
	private static String getElementValue(Document doc, String elementName) {
		NodeList nodeLst = doc.getElementsByTagName(elementName);
		
		Element fstNmElmnt = (Element) nodeLst.item(0);
		String value = null; 
		
		if(fstNmElmnt!=null) {
			NodeList fstNm = fstNmElmnt.getChildNodes();
			
			if(((Node) fstNm.item(0))!=null) {
				value = ((Node) fstNm.item(0)).getNodeValue();
			} else {
				value = "";
			}			
		}
		
		return value;
	}   
}
